package com.atguigu.tingshu.album.listener;

import com.atguigu.tingshu.album.service.TrackInfoService;
import com.atguigu.tingshu.common.constant.RabbitConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

// 接收消息 更新声音的统计信息
@Slf4j
@Component
public class AlbumMqListener {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private TrackInfoService trackInfoService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = RabbitConstant.TRACK_STAT_QUEUE, durable = "true"),
                    exchange = @Exchange(value = RabbitConstant.ALBUM_EXCHANGE, type = "topic", durable = "true"),
                    key = RabbitConstant.TRACK_STAT_RK
            )
    )
    public void updateTrackStat(Channel channel, Message message, TrackStatMqVo trackStatMqVo) throws IOException {
        // albumId的没有发送的哦
        // 幂等性校验
        String businessNo = trackStatMqVo.getBusinessNo();
        // 拼接key
        String key = RedisConstant.TRACK_STAT_IDEM + businessNo;
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(key, 1, 10, TimeUnit.MINUTES);
        if(!flag){
            log.error("更新声音的播放量消息{},重复发送",trackStatMqVo.getTrackId());
            // 拒绝消息
            channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
            return;
        }
        try {
            // 更新声音和专辑的播放量
            trackInfoService.updateTrackStat(trackStatMqVo);
            log.info("更新声音的播放量消息,消息消费成功。消息：{}", trackStatMqVo.getTrackId());
        }catch (Exception e){

            // 判断消息是否已经重新投递了一次
            if(message.getMessageProperties().getRedelivered()){
                // 拒绝并且丢弃消息
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, false);
                log.error("更新声音的播放量消息{},消费失败........",trackStatMqVo.getTrackId());
            }else{
                // 重新投递消息
                // 第一次消费异常时候 需要删除key
                log.error("更新声音的播放量消息{},消费失败,正在进行重试......",trackStatMqVo.getTrackId());
                redisTemplate.delete(key);
                channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            }
        }



    }
}
